<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Modules extends MY_ADMIN_Controller{
	
	function __construct()
	{
		parent::__construct();
		$this->loadModel('Module_model','Module');
	}
	
	function index() {	
		$condition = array(
			'order'=>array('sorts'=>'DESC')
		);
		$result = $this->Module->find($condition);
		$this->assign['moduleList'] = $result;
		$this->display();
	}
	
	/**
	 * 添加模块
	 */
	function create(){
		if($this->input->post(null,true)){
			return $this->save('modules/create');
		}else{
			$this->display();
		}
	}
	
	/**
	 * 保存模块
	 */
	private function save($type=''){
		$redirect = getRedirect(base_url('admin/modules'));
		
		$this->load->library('form_validation');
		$this->lang->load('template');
		
		if ($this->form_validation->run($type) == FALSE){
			return $this->showMessage(validation_errors(), $redirect); 
		}
		
		if(($id = $this->Module->save($this->input->post(null,true)))!==false){
			$mes = 'mes_success';
			//清空缓存文件
			$this->clearModuleCache();
			return $this->showMessage($mes,$redirect);
		}else{
			return $this->showMessage($this->Module->_error, $redirect); 
		}
	}

	/**
	 * 编辑模块
	 */
	function edit($id){
		if($this->input->post(null,true)){
			return $this->save('modules/edit');
		}else{
			$res = $this->Module->findByPk($id);
			if(empty($res)){
				return $this->showMessage('error_param',site_url('admin/modules'));
			}
			$this->assign['module'] = $res[0];
			$this->display();
		}
	}
	
	/**
	 * 删除模块（只允许删除没有子模块的）
	 */
	function remove($id=null){
		$redirect = getRedirect(base_url('admin/modules'));
		$id = $id>0?$id:intval($this->input->get('id',true));
		$res = $this->Module->findByPk($id);
		if(empty($res)){
			return $this->showMessage('error_param',site_url('admin/modules'));
		}
		$cond = array('where'=>array('parent_id'=>$res[0]['id']));
		$result = $this->Module->find($cond);
		if(!empty($result)){
			return $this->showMessage('error_has_sub',site_url('admin/modules'));
		}
		if($this->Module->removeByPks($id) === true){
			$mes = 'mes_success';
			$this->clearModuleCache();
			return $this->showMessage($mes,site_url('admin/modules'));
		}
		return $this->showMessage('failure',site_url('admin/modules'));
	}
	
	private function clearModuleCache(){
		$file = realpath(APPPATH).'/tmp/~sys_modules.php';
		if(file_exists( $file )){
			@chmod( $file ,0777);
			@unlink($file);
		}
	}
}
/* End of file modules.php */
/* Location: ./application/controllers/admin/modules.php */